package com.atguigu.gmall.all.controller;


import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
public class IndexController {

    @Resource
    private ProductFeignClient productFeignClient;

    // static /webapp/index.html
    // templates  WEB-INF/index/index.html
    //首页  https://www.jd.com/     www.gmall.com
    @GetMapping("/")
    public String index(Model model) {

        List<Map> listMap1 = new ArrayList<>();
        List<BaseCategoryView> baseCategoryViewList = productFeignClient.getBaseCategoryViewList();
        //根据一级分类ID 进行分组 返回值 Map
        Map<Long, List<BaseCategoryView>> baseCategoryViewListMap = baseCategoryViewList
                .stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        baseCategoryViewListMap.forEach((k, v) -> {
            //一级分类
            Map category1Map = new HashMap();
            category1Map.put("index", k);
            category1Map.put("categoryId", k);
            category1Map.put("categoryName", v.get(0).getCategory1Name());

            //二级分类
            Map<Long, List<BaseCategoryView>> baseCategoryView2ListMap = v
                    .stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
            List<Map> listMap2 = new ArrayList<>();
            baseCategoryView2ListMap.forEach((k2, v2) -> {
                Map category2Map = new HashMap();
                category2Map.put("categoryId", k2);
                category2Map.put("categoryName", v2.get(0).getCategory2Name());
                //3:三级分类
                List<Map> listMap3 = new ArrayList<>();
                v2.forEach(baseCategoryView -> {
                    Map category3Map = new HashMap();
                    category3Map.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Map.put("categoryName",baseCategoryView.getCategory3Name());
                    listMap3.add(category3Map);
                });
                category2Map.put("categoryChild",listMap3);
                listMap2.add(category2Map);
            });
            category1Map.put("categoryChild",listMap2);
            listMap1.add(category1Map);
        });
        model.addAttribute("list",listMap1);
        return "index/index";
    }
}
